﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Subsidiary.CouponWrapper
{
    public class JingDongCouponWrapper : ICouponWrapper
    {
        public static readonly string trPattern = @"<tr.*?class=""tr01""[^>]*>(.*?)</tr>";
        public static readonly string tdNumberPattern = @"<td>(\d+?)</td>";
        public static readonly string tdNamePattern = @"<span>(.+?)</span>";
        public static readonly string tdBalancePattern = @"<div class=""ar ftx-01"">\s*￥(\d+\.\d{2})";
        public static readonly string tdAcmountPattern = @"<div class=""ar"">\s*￥(\d+\.\d{2})";
        public static readonly string tdEndPattern = @"(<div class=""datelimit"">\s*?)(\d.*\d)</div>";
        public static readonly string tdLimitPattern = @"<p class=""u-limit"">\s+(.+)</p>";
        public List<CouponItem> PickUp(string html)
        {
            List<CouponItem> coupons = new List<CouponItem>();
            Match trMatch = Regex.Match(html, trPattern);
            while (trMatch != null && trMatch.Success) 
            {
                string trHtml = trMatch.Groups[1].Value;
                Match nameMatch = Regex.Match(trHtml, tdNamePattern);
                Match balanceMatch = Regex.Match(trHtml, tdBalancePattern);
                Match amountMatch = Regex.Match(trHtml, tdAcmountPattern);
                Match endMatch = Regex.Match(trHtml, tdEndPattern);
                Match limitMatch = Regex.Match(trHtml, tdLimitPattern);
                Match numberMatch = Regex.Match(trHtml, tdNumberPattern);
                //Match nameMatch = Regex.Match(trHtml, tdNamePattern);
                CouponItem coupon = new CouponItem
                {
                    Title = nameMatch.Groups[1].Value,
                    Shop = "京东",
                    Link = "http://www.360buy.com/",
                    EndDate = endMatch.Groups[1].Value,
                    Number = numberMatch.Groups[1].Value,
                    Password = string.Empty,
                    Amount = float.Parse(balanceMatch.Groups[1].Value),
                    Comment = string.Format("购买总额达到{0}元可以用，{1}", amountMatch.Groups[1].Value, limitMatch.Groups[1].Value)
                };
                coupons.Add(coupon);
                trMatch = trMatch.NextMatch();
            }
            return coupons;
        }
    }
}
